import redis
import pymongo
import logging
import os
import datetime

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/diversity_layer.log'),
        logging.StreamHandler()
    ]
)

class DiversityLayer:
    def __init__(self):
        # 创建日志目录
        os.makedirs('logs', exist_ok=True)
        
        # 获取日志记录器
        self.logger = logging.getLogger(__name__)
        
        # 连接MongoDB
        try:
            self.mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
            self.db = self.mongo_client["farmer"]
            self.collection = self.db["孜然"]
            self.logger.info("MongoDB连接成功")
        except Exception as e:
            self.logger.error(f"MongoDB连接失败: {e}")
            raise
        
        # 连接Redis
        try:
            self.redis_client = redis.Redis(host='localhost', port=16379, db=1)
            self.logger.info("Redis连接成功")
        except Exception as e:
            self.logger.error(f"Redis连接失败: {e}")
            raise
    
    def apply_diversity(self, ranked_list, user_id):
        self.logger.info(f"开始对用户 {user_id} 的推荐结果进行多样性优化")
        try:
            selected = []
            used_categories = set()
            
            for product_id, _ in ranked_list:
                product = self.collection.find_one({"_id": product_id})
                if not product:
                    self.logger.warning(f"商品 {product_id} 未找到")
                    continue
                
                if product["category"] not in used_categories:
                    selected.append(product_id)
                    used_categories.add(product["category"])
                    if len(selected) >= 5:  # 最多推荐5个商品
                        break
            
            # 将推荐结果存储到Redis
            try:
                self.redis_client.set(f"recommendations:user:{user_id}", ",".join(selected))
                self.redis_client.expire(f"recommendations:user:{user_id}", 3600)  # 设置过期时间为1小时
                self.logger.info(f"推荐结果已存储到Redis，用户ID: {user_id}")
            except Exception as e:
                self.logger.error(f"Redis存储失败: {e}")
            
            self.logger.info(f"多样性优化完成，最终推荐商品数量: {len(selected)}")
            return selected
        except Exception as e:
            self.logger.error(f"多样性优化失败: {e}")
            return []